<template>
  <div>
    <!-- 遍历 posts 数组 -->
    <div v-for="post in posts" :key="post.id" class="forum-post">
      <!-- 用户信息 -->
      <div class="user-info">
        <img :src="post.user.avatar" alt="User Avatar" class="user-avatar" />
        <div class="user-details">
          <h3>{{ post.user.name }}</h3>
          <p class="post-time">{{ post.time }}</p>
        </div>
      </div>

      <!-- 用户发布的内容 -->
      <div class="post-content">
        <p class="post-text">{{ post.text }}</p>
        <div class="post-images">
          <!-- 显示图片，最多显示9张 -->
          <img
              v-for="(image, index) in post.images.slice(0, 9)"
              :key="index"
              :src="image"
              alt="Post Image"
              class="post-image"
              @click="openImage(image)"
          />
        </div>
      </div>

      <!-- 功能按钮 -->
      <div class="actions">
        <button @click="likePost(post)" :class="{ liked: post.liked }">
          👍 {{ post.likes }}
        </button>
        <button @click="collectPost(post)" :class="{ collected: post.collected }">
          💖 收藏
        </button>
        <button @click="sharePost(post)">
          🔁 转发
        </button>
      </div>
    </div>

    <!-- 大图查看模态框 -->
    <div v-if="isImageModalOpen" class="image-modal" @click="closeImage">
      <img :src="currentImage" alt="Large Image" class="modal-image" />
    </div>
  </div>
</template>

<script>
import {
  findAllActivity,
  updateStatus,
  collect,
  findAllLike,
  findAllCollect,
  forward,
} from "../../api/user.js";

export default {
  data() {
    return {
      posts: [], // 存储多个帖子
      isImageModalOpen: false,
      currentImage: "",
    };
  },
  methods: {
    // 获取动态数据
    async fetchPosts() {
      try {
        const response = await findAllActivity();
        console.log('后端返回的数据：', response.data);

        // 确保数据格式正确
        if (response.data && Array.isArray(response.data)) {
          const user = JSON.parse(localStorage.getItem('user'));
          if (!user || !user.id) {
            alert('用户信息缺失，请重新登录');
            return;
          }

          // 获取用户点赞和收藏的列表
          const likesResponse = await findAllLike(user.id);
          console.log('后端返回的点赞数据：', likesResponse.data);
          const collectsResponse = await findAllCollect(user.id);
          console.log('后端返回的收藏数据：', collectsResponse.data);

          // 提取点赞和收藏的动态 ID
          const likedPostIds = likesResponse.data.data.map(like => like.cid); // 使用 cid 字段
          const collectedPostIds = collectsResponse.data.data.map(collect => collect.cid); // 使用 cid 字段

          console.log('用户点赞的动态 ID 列表：', likedPostIds);
          console.log('用户收藏的动态 ID 列表：', collectedPostIds);

          // 初始化 posts
          this.posts = response.data.map((item) => ({
            id: item.id,
            user: {
              name: item.username || 'user', // 默认值为 'user'
              avatar: '/src/assets/mylogo.png', // 默认头像
            },
            text: item.content || '暂无内容', // 默认值为 '暂无内容'
            time: this.formatDate(item.publishDate), // 格式化时间
            images: item.images ? [item.images] : [], // 将单张图片转换为数组
            likes: item.likes || 0, // 默认值为 0
            liked: likedPostIds.includes(item.id.toString()), // 检查是否已点赞
            collected: collectedPostIds.includes(item.id.toString()), // 检查是否已收藏
          }));

          console.log('初始化后的 posts：', this.posts);
        } else {
          console.error('后端返回的数据格式不正确');
        }
      } catch (error) {
        console.error('获取动态数据失败：', error);
      }
    },
    // 格式化时间
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString(); // 根据本地格式显示时间
    },
    // 点赞
    likePost(post) {
      const user = JSON.parse(localStorage.getItem('user'));
      if (!user || !user.id) {
        alert('用户信息缺失，请重新登录');
        return;
      }

      const data = {
        id: user.id,
        likeid: post.id,
      };

      if (post.liked) {
        updateStatus(data).then(() => {
          alert('取消点赞');
          post.liked = false;
          post.likes -= 1;
        }).catch(error => {
          console.error('取消点赞失败:', error);
        });
      } else {
        updateStatus(data).then(() => {
          alert('点赞成功');
          post.liked = true;
          post.likes += 1;
        });
      }
    },
    // 收藏
    collectPost(post) {
      const user = JSON.parse(localStorage.getItem('user'));
      if (!user || !user.id) {
        alert('用户信息缺失，请重新登录');
        return;
      }

      const data = {
        user_id: user.id,
        c_id: post.id,
      };

      if (post.collected) {
        collect(data.id).then(() => {
          alert('取消收藏');
          post.collected = false;
        }).catch(error => {
          console.error('取消收藏失败:', error);
        });
      } else {
        collect(data).then(() => {
          alert('收藏成功');
          post.collected = true;
        });
      }
    },
    // 转发
    sharePost(post) {
      forward(post);
      alert('已转发');
    },
    // 打开图片
    openImage(image) {
      this.currentImage = image;
      this.isImageModalOpen = true;
    },
    // 关闭图片
    closeImage() {
      this.isImageModalOpen = false;
    },
    // 触发文件选择对话框
    triggerFileSelect() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      this.uploadFile(file);
    },
    // 执行上传的axios方法
    async uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);

      try {
        const response = await upload(formData);

        // 上传成功处理
        if (response.status === 200) {
          this.post.images.push(response.data); // 将返回的路径添加到图片列表
          this.$message.success('文件上传成功');
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error(`上传失败: ${error.response?.data || error.message}`);
      }
    },
  },
  mounted() {
    this.fetchPosts(); // 组件加载时获取动态数据
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.forum-post {
  border: 1px solid #ddd;
  padding: 16px;
  margin: 16px 0;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-details h3 {
  margin: 0;
  font-size: 18px;
}

.post-content {
  margin-top: 16px;
}

.post-text {
  text-align: left;
  margin-bottom: 16px;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.post-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
}

.actions {
  margin-top: 16px;
  display: flex;
  gap: 10px;
}

.actions button {
  padding: 8px 12px;
  background-color: rgba(0, 132, 255, 0.7);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.actions button.liked {
  background-color: rgba(255, 77, 77, 0.7);
}

.actions button.collected {
  background-color: rgba(255, 204, 0, 0.7);
}

.actions button:hover {
  background-color: rgba(0, 132, 255, 0.9);
}

.actions button.liked:hover {
  background-color: rgba(255, 77, 77, 0.9);
}

.actions button.collected:hover {
  background-color: rgba(255, 204, 0, 0.9);
}

.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-image {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
}
</style>